package com.linrung.sf.scheduler.zwwx.service;

import com.linrung.core.model.ResultData;
import com.linrung.sf.scheduler.zwwx.entity.WarnEntity;
import com.linrung.sf.scheduler.zwwx.entity.ZwwxMessageEntity;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @Module 预警消息服务
 * @Author Linyubang
 * @Date 2023 11 24
 **/
@Service("WarnMessageSendService")
public class WarnMessageSendService {

    private static Logger logger = Logger.getLogger(WarnMessageSendService.class);

    @Autowired
    @Qualifier("jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    public void genAppealAcceptOutTime(String reasonTpl,String msgTpl) {
        String sql = "select n.id as code,n.typeName,n.title,t.reachtime,t.nodeName,t.acceptdeptid as deptId,t.acceptdeptname as deptName,t.id,t.lastaccepttimelimit as warnTime " +
                        " from LR_SF_APPEAL_NODE t left join LR_SF_APPEAL n on t.appealid=n.id " +
                        " where t.delstate='0' and t.handlestate='0' and t.lastaccepttimelimit is not null and t.lastaccepttimelimit<? and t.iswarn='1' " +
                        " and not EXISTS(select 1 from LR_SF_SV_WARN w where w.businessid=t.id and w.warndeptid=t.acceptdeptid and w.businesstype='1') ";
        this.genWarnRecord(sql,"1",reasonTpl,msgTpl);
    }

    public void genAppealHandleOutTime(String reasonTpl,String msgTpl) {
        String sql = "select n.id as code,n.typeName,n.title,t.reachtime,t.nodeName,t.acceptdeptid as deptId,t.acceptdeptname as deptName,t.id,t.lasthandletimelimit as warnTime " +
                " from LR_SF_APPEAL_NODE t left join LR_SF_APPEAL n on t.appealid=n.id " +
                " where t.delstate='0' and t.handlestate='1' and t.lasthandletimelimit is not null and t.lasthandletimelimit<? and t.iswarn='1' " +
                " and not EXISTS(select 1 from LR_SF_SV_WARN w where w.businessid=t.id and w.warndeptid=t.acceptdeptid and w.businesstype='2') ";
        this.genWarnRecord(sql,"2",reasonTpl,msgTpl);
    }

    public void genWorkTaskHandleOutTime(String reasonTpl,String msgTpl) {
        String sql = "select n.id as code,n.taskrelobjecttypename as typeName,n.taskname title,t.createtime as reachtime,'待处理任务' as nodeName,t.handledeptid as deptId,t.handledeptname as deptName,t.id,t.lasthandletime as warnTime " +
                " from LR_SF_WORKTASK_DEAL t left join LR_SF_WORKTASK n on t.taskid=n.id " +
                " where t.delstate='1' and t.handlestate='0' and t.lasthandletime is not null and t.lasthandletime<? and t.iswarn='1' " +
                " and not EXISTS(select 1 from LR_SF_SV_WARN w where w.businessid=t.id and w.warndeptid=t.handledeptid and w.businesstype='3') ";
        this.genWarnRecord(sql,"3",reasonTpl,msgTpl);
    }

    public void genPreAppealHandleOutTime(String reasonTpl,String msgTpl) {
        String sql = "select n.id as code,'公众上报事件' as typeName,n.title,n.updatestatetime as reachtime,'待预受理事件' as nodeName, " +
                " t.handledeptid as deptId,g.org_name as deptName,t.id,t.warntime " +
                " from LR_SF_WX_APPEAL_PRE_WARN t left join LR_SF_WX_APPEAL n on t.appealid=n.id and t.updatestateid=n.updatestateid " +
                " left join lr_pf_org g on t.handledeptid=g.id " +
                " where t.warnstate='0' and n.state in ('1','2','3') and t.warntime<? and n.iswarn='1' " +
                " and not EXISTS(select 1 from LR_SF_SV_WARN w where w.businessid=t.updatestateid and w.warndeptid=t.handledeptid and w.businesstype='5') ";
        this.genWarnRecord(sql,"5",reasonTpl,msgTpl);
    }

    private String getTplContent(String tpl,String code, String title, String typeName,String nodeName, String deptName){
        typeName = typeName!= null?typeName:"";
        String content = tpl.replace("{code}", code);
        content = content.replace("{title}", title);
        content = content.replace("{typeName}", typeName);
        content = content.replace("{nodeName}", nodeName);
        content = content.replace("{deptName}", deptName);
        return content;
    }

    public void genWarnRecord(String sql,String businessType,String reasonTpl,String msgTpl) {
        List<WarnEntity> list = new ArrayList<WarnEntity>();
        //1、先生成事件受理逾期记录
        SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql,new Object[]{new Date()});
        while (rs.next()) {
            WarnEntity entity = new WarnEntity();
            entity.setCode(rs.getString("code"));
            entity.setBusinessId(rs.getString("id"));
            entity.setBusinessType(businessType);
            entity.setWarnType("2");
            entity.setWarnReason(this.getTplContent(reasonTpl, rs.getString("code"), rs.getString("title"), rs.getString("typeName"), rs.getString("nodeName"), rs.getString("deptName")));
            entity.setWarnTime(rs.getTimestamp("warnTime"));
            entity.setWarnDeptId(rs.getString("deptId"));
            entity.setMsgContent(this.getTplContent(msgTpl, rs.getString("code"), rs.getString("title"), rs.getString("typeName"), rs.getString("nodeName"), rs.getString("deptName")));
            entity.setMsgState("0");
            list.add(entity);
        }
        String updateAppeal = "update LR_SF_APPEAL set warnstate=? where id=? ";
        String updateNode = "update LR_SF_APPEAL_NODE set warnstate=? where id=? ";
        String updateWorkTask = "update LR_SF_WORKTASK set warnstate=? where id=? ";
        String updateWorkTaskDeal = "update LR_SF_WORKTASK_DEAL set warnstate=? where id=? ";
        String updateWxPreAppeal = "update LR_SF_WX_APPEAL set warnstate=? where id=? ";
        String updateWxPreAppealWarn = "update LR_SF_WX_APPEAL_PRE_WARN set warnstate=? where id=? ";
        String insert = "insert into LR_SF_SV_WARN(id,businessId,businessType,warnType,warnReason,warnTime,warnDeptId,msgContent,msgState) values(?,?,?,?,?,?,?,?,?) ";
        for (WarnEntity e : list) {
            this.jdbcTemplate.update(insert, new Object[]{UUID.randomUUID().toString(), e.getBusinessId(), e.getBusinessType(), e.getWarnType(), e.getWarnReason(),
                    e.getWarnTime(), e.getWarnDeptId(), e.getMsgContent(), e.getMsgState()});
            if(businessType.equals("1") || businessType.equals("2")) {
                this.jdbcTemplate.update(updateAppeal, new Object[]{e.getWarnType(), e.getCode()});
                this.jdbcTemplate.update(updateNode, new Object[]{e.getWarnType(), e.getBusinessId()});
            }else if(businessType.equals("3")) {
                this.jdbcTemplate.update(updateWorkTask, new Object[]{e.getWarnType(), e.getCode()});
                this.jdbcTemplate.update(updateWorkTaskDeal, new Object[]{e.getWarnType(), e.getBusinessId()});
            }else if(businessType.equals("5")) {
                this.jdbcTemplate.update(updateWxPreAppeal, new Object[]{e.getWarnType(), e.getCode()});
                this.jdbcTemplate.update(updateWxPreAppealWarn, new Object[]{e.getWarnType(), e.getBusinessId()});
            }
        }
        logger.info(String.format("本次要生成逾期(%s)总条数 = %d",businessType,list.size()));
        list.clear();
    }

    private static Map<String,String> typeMap = new HashMap<String,String>();
    static {
        //1事件受理 2事件处理 3专项办理 4专项整治
        typeMap.put("1","事件受理");
        typeMap.put("2","事件办理");
        typeMap.put("3","专项办理");
        typeMap.put("4","专项整治");
        typeMap.put("5","事件预受理");
    }

    public void genWarnNoticeMessage() {
        List<ZwwxMessageEntity> list = new ArrayList<ZwwxMessageEntity>();
        String sql = "select t.id,t.businesstype as msgType,t.msgcontent,t.warntime,t.businessid,t.warndeptid,t2.id as userid,t2.syncuserid from LR_SF_SV_WARN t " +
                      " left join lr_pf_user_org t1 on t.warndeptid=t1.org_id " +
                      " left join lr_pf_user t2 on t1.user_id=t2.id " +
                      " where t.msgstate='0' " +
                      " and exists (select 1 from lr_pf_user_role r left join lr_pf_role r1 on r.role_id=r1.id " +
                      " where r1.role_key in ('ROLE_DEPT_ROLE','ROLE_GRID_ROLE','ROLE_ZJGLY_MGR','ROLE_CJGZZ_MGR') and r.user_id=t2.id ) ";
        //1、先生成待发送的消息
        SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql);
        while (rs.next()) {
            ZwwxMessageEntity entity = new ZwwxMessageEntity();
            entity.setMsgType("9");
            entity.setBusinessKeyId(rs.getString("id"));
            entity.setTitle(rs.getString("msgcontent"));
            entity.setSource(typeMap.get(rs.getString("msgType"))+"逾期提醒");
            entity.setRemindTime(new Date());
            entity.setSender("系统");
            entity.setSenderDept("系统");
            entity.setReceiverId(rs.getString("userid"));
            entity.setReceiverSyncUserId(rs.getString("syncuserid"));
            list.add(entity);
        }
        String update = "update LR_SF_SV_WARN set msgstate='1' where id=? ";
        String insert = "insert into lr_sf_message(id,msgtype,bkeyid,title,subtitle,sourceuser,sourcedept,reachtime,receiverid,receiversyncuserid,createtime) values(?,?,?,?,?,?,?,?,?,?,sysdate) ";
        for (ZwwxMessageEntity e : list) {
            this.jdbcTemplate.update(insert, new Object[]{UUID.randomUUID().toString(), e.getMsgType(), e.getBusinessKeyId(), e.getTitle(), e.getSource(),
                    e.getSender(), e.getSenderDept(), e.getRemindTime(), e.getReceiverId(), e.getReceiverSyncUserId()});
            this.jdbcTemplate.update(update, new Object[]{e.getBusinessKeyId()});
        }
        logger.info(String.format("本次要生成待发送消息(%s)总条数 = %d", "逾期提醒",list.size()));
        list.clear();
    }

    public List<ZwwxMessageEntity> loadNoNoticeMessageList(){
        List<ZwwxMessageEntity> list = new ArrayList<ZwwxMessageEntity>();
        //1、读取待发送消息
        String msgSql = "select a.* from lr_sf_message a where a.sendstate='0' and a.msgtype='9' and a.createtime>sysdate-2 order by a.createtime desc";
        SqlRowSet mr = this.jdbcTemplate.queryForRowSet(msgSql);
        while(mr.next()){
            ZwwxMessageEntity entity = new ZwwxMessageEntity();
            entity.setId(mr.getString("id"));
            entity.setBusinessKeyId(mr.getString("bkeyid"));
            entity.setTitle(mr.getString("title"));
            entity.setSource(mr.getString("subtitle"));
            entity.setRemindTime(mr.getTimestamp("reachtime"));
            entity.setSender(mr.getString("sourceuser"));
            entity.setSenderDept(mr.getString("sourcedept"));
            entity.setReceiverId(mr.getString("receiverid"));
            entity.setReceiverSyncUserId(mr.getString("receiversyncuserid"));
            entity.setCreateTime(new Date());
            entity.setMessageType(0);//卡片链接
            list.add(entity);
        }
        return list;
    }

    /**
     * 生成督办通知消息
     */
    public void genSuperviseNoticeMessage() {
        List<ZwwxMessageEntity> list = new ArrayList<ZwwxMessageEntity>();
        String sql = "select t.id,t.content as msgcontent,t.createtime as sendtime,t.wordgrid_id,t2.id as userid,t2.syncuserid from LR_SFZ_GIRD_MSG t " +
                "   left join lr_pf_user_org t1 on t.wordgrid_id=t1.org_id " +
                "    left join lr_pf_user t2 on t1.user_id=t2.id " +
                "    where t.sendstate='0' " +
                "    and exists (select 1 from lr_pf_user_role r left join lr_pf_role r1 on r.role_id=r1.id " +
                "    where r1.role_key in ('ROLE_GRID_ROLE') and r.user_id=t2.id ) ";
        //1、先生成待发送的消息
        SqlRowSet rs = this.jdbcTemplate.queryForRowSet(sql);
        while (rs.next()) {
            ZwwxMessageEntity entity = new ZwwxMessageEntity();
            entity.setMsgType("9");
            entity.setBusinessKeyId(rs.getString("id"));
            entity.setTitle(rs.getString("msgcontent"));
            entity.setSource("督办通知");
            entity.setRemindTime(new Date());
            entity.setSender("系统");
            entity.setSenderDept("系统");
            entity.setReceiverId(rs.getString("userid"));
            entity.setReceiverSyncUserId(rs.getString("syncuserid"));
            list.add(entity);
        }
        String update = "update LR_SFZ_GIRD_MSG set sendstate='1' where id=? ";
        String insert = "insert into lr_sf_message(id,msgtype,bkeyid,title,subtitle,sourceuser,sourcedept,reachtime,receiverid,receiversyncuserid,createtime) values(?,?,?,?,?,?,?,?,?,?,sysdate) ";
        for (ZwwxMessageEntity e : list) {
            this.jdbcTemplate.update(insert, new Object[]{UUID.randomUUID().toString(), e.getMsgType(), e.getBusinessKeyId(), e.getTitle(), e.getSource(),
                    e.getSender(), e.getSenderDept(), e.getRemindTime(), e.getReceiverId(), e.getReceiverSyncUserId()});
            this.jdbcTemplate.update(update, new Object[]{e.getBusinessKeyId()});
        }
        logger.info(String.format("本次要生成待发送消息(%s)总条数 = %d", "督办通知",list.size()));
        list.clear();
    }

    public void updateReceiverWxSendStateById(String msgId,String state){
        String update = "update lr_sf_message set SENDSTATE=?,SENDTIME=sysdate where id=? ";
        this.jdbcTemplate.update(update,new Object[]{state,msgId});
    }

    /**
     * 发送短信
     * @param messageSendEntity
     * @param isNeedPrefixes
     * @param isNeedSuffixes
     */
    public ResultData addMessageSend(ZwwxMessageEntity messageSendEntity, String isNeedPrefixes, String isNeedSuffixes) {
        ResultData rs = new ResultData();
        rs.setState(1);
        return rs;
    }

    /**
     * 发送短信
     * @param messageSendEntity
     */
    public ResultData addMessageSend(ZwwxMessageEntity messageSendEntity) {
        return this.addMessageSend(messageSendEntity,null,null);
    }

}
